<?php
require_once('simpletest/autorun.php');
require_once("../src/scottlib.php");
require_once("_ormTestClasses.php");

/**
 * Unit tests for scottlib ORM
 * @author Aaron Collegeman aaroncollegeman.com
 * @since 0.1.3
 */
class TestOrm extends UnitTestCase {
	
	function setUp() {
		connect(':/tmp/mysql.sock', 'root', 'password', 'scottlib');
		slObject::create(new Widget());
		slObject::create(new OrmClassWithAutoTimestampingEnabled());
		slObject::create(new OrmClassWithAutoTimestampingDisabled());
	}	
	
	function testIdPropertyDetection() {
		$obj = new OrmClassWithImplicitId();
		$obj->id = 'foo';
		$this->assertEqual('foo', $obj->getId());
		
		$obj = new OrmClassWithExplicitId();
		$obj->foo = 'bar';
		$this->assertEqual('bar', $obj->getId());
	}
	
	function testAutoTimestamping() {
		// first, autotimestamp enabled
		$obj = new OrmClassWithAutoTimestampingEnabled();
		$obj->save();	
		$this->assertNotNull($obj->dateCreated);
		$this->assertTrue(strtotime($obj->dateCreated) !== false);
		$this->assertEqual($obj->dateCreated, $obj->lastUpdated);
		
		// brief pause 
		$now = time();
		while (time() == $now) {}
		
		// on second save, lastUpdated should be different
		$obj->save();
		$this->assertNotNull($obj->dateCreated);
		$this->assertNotNull($obj->lastUpdated);
		$this->assertTrue(strtotime($obj->dateCreated) < strtotime($obj->lastUpdated));
	
		// second, autotimestamp disabled
		$obj = new OrmClassWithAutoTimestampingDisabled();
		$obj->save();
		$this->assertNull($obj->dateCreated);
		$this->assertNull($obj->lastUpdated);
	}
	
	function tearDown() {
		slObject::drop(new Widget());
		slObject::drop(new OrmClassWithAutoTimestampingEnabled());
		slObject::drop(new OrmClassWithAutoTimestampingDisabled());
	}
	
}

class OrmClassWithImplicitId extends slObject {}
	
class OrmClassWithExplicitId extends slObject {

	/** @id */
	public $foo;
	
}

class OrmClassWithAutoTimestampingEnabled extends slObject {

	/** @date */
	public $dateCreated;
	
	/** @date */
	public $lastUpdated;
	
}

/** @autoTimestamp(false) */
class OrmClassWithAutoTimestampingDisabled extends slObject {
	
	/** @date */
	public $dateCreated;
	
	/** @date */
	public $lastUpdated;
	
}

class OrmClassWithOneToManyRelationship extends slObject {

	/** @hasMany(Widget) */
	public $widgets;
	
}

/**
 * The Widget class is used to test various relationship types and autotimestamping.
 */
class Widget extends slObject {
	
	public $name;
	
}

